<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 卡片区域 -->
      <el-card class="box-card">
        <!-- 添加按钮 -->
        <el-button
          type="success"
          size="small"
          icon="el-icon-edit"
          class="addBtn"
          @click="addDialogVisible=true"
        >添加菜单</el-button>

        <!-- 表格区域 -->
        <el-table
          :data="menuslist"
          style="width: 100%"
          row-key="id"
          default-expand-all
          :tree-props="{children: 'childs'}"
        >
          <el-table-column prop="title" label="标题" width="200px">
            <template slot-scope="scope">
              <i v-if="scope.row.pid===null" class="menus-icon fa fa-folder-open-o fa-fw"></i>
              <i v-else-if="scope.row.is_point" class="menus-icon el-icon-view"></i>
              <i v-else class="menus-icon fa fa-file-o fa-fw"></i>
              <span>{{scope.row.title}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="code" label="权限点代码"></el-table-column>
          <el-table-column label="操作" class="btn" width="120px" align="center">
            <template slot-scope="scope">
              <el-button
                type="primary"
                plain
                icon="el-icon-edit"
                circle
                @click="onEditMenus(scope.row)"
              ></el-button>
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                circle
                @click="deleteMenus(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 添加菜单弹框 -->
      <el-dialog
        title="创建菜单"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogVisibleClosed"
      >
        <!-- 表格区域 -->
        <el-form :model="addMenus" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item label="权限组名称">
            <el-radio v-model="type" label="menus">菜单</el-radio>
            <el-radio v-model="type" label="points">权限点</el-radio>
          </el-form-item>

          <el-form-item label="权限组名称">
            <!-- 菜单级联选择器 -->
            <el-cascader
              v-if="type==='menus'"
              clearable
              v-model="selectKeys"
              :props="menusProps"
              :options="newMenuslist"
            ></el-cascader>
            <!-- 权限点级联选择器 -->
            <el-cascader
              v-else
              clearable
              v-model="selectKeys"
              :props="pointsProps"
              :options="newMenuslist"
            ></el-cascader>
          </el-form-item>

          <el-form-item label="权限代码" prop="code">
            <el-input v-model="addMenus.code"></el-input>
          </el-form-item>
          <el-form-item label="权限标题" prop="title">
            <el-input v-model="addMenus.title"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible=false">取 消</el-button>
          <el-button type="primary" @click="onAddMenus">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑菜单、权限点弹框 -->
      <el-dialog
        destroy-on-close
        title="编辑菜单"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogVisibleClosed"
      >
        <!-- 表格区域 -->
        <el-form :model="editMenus" :rules="editFormRules" ref="editFormRef" label-width="100px">
          <el-form-item label="权限组名称">
            <el-radio v-model="type" label="menus" disabled>菜单</el-radio>
            <el-radio v-model="type" label="points" disabled>权限点</el-radio>
          </el-form-item>

          <el-form-item label="权限组名称">
            <!-- 菜单级联选择器 -->
            <el-cascader v-model="selectKeys" :props="menusProps" :options="newMenuslist"></el-cascader>
          </el-form-item>

          <el-form-item label="权限代码" prop="code">
            <el-input v-model="editMenus.code"></el-input>
          </el-form-item>
          <el-form-item label="权限标题" prop="title">
            <el-input v-model="editMenus.title"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible=false">取 消</el-button>
          <el-button type="primary" @click="sureEditMents">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { list as getMenusList, remove as removeMenus, add as currentAdd, detail as getDetail, update as updateMenus } from '@/api/base/menus'

export default {
  name: 'Menus',
  data() {
    return {
      menuslist: [],
      newMenuslist: [], // 渲染级联选择器数据
      addDialogVisible: false,
      type: 'menus',
      value: null,
      selectKeys: [], // 级联选择器数组
      menusProps: {
        children: 'childs',
        label: 'title',
        value: 'id',
        checkStrictly: true
      },
      pointsProps: {
        children: 'childs',
        label: 'title',
        value: 'id'
      },
      addMenus: {
        code: '',
        title: ''
      },
      addPoints: {
        code: '',
        title: ''
      },
      addFormRules: {
        code: [{ required: true, message: '代码不能为空', trigger: 'blur' }],
        title: [{ required: true, message: '权限不能为空', trigger: 'blur' }]
      },
      editMenus: {},
      editFormRules: {
        code: [{ required: true, message: '代码不能为空', trigger: 'blur' }],
        title: [{ required: true, message: '权限不能为空', trigger: 'blur' }]
      },
      editDialogVisible: false
    }
  },
  computed: {
    cateId() {
      if (this.selectKeys.length === 2) {
        return this.selectKeys[1]
      } else {
        return this.selectKeys[0]
      }
    }
  },
  created() {
    this.loadMenusList()
  },
  mounted() {},
  methods: {
    // 获取菜单列表
    async loadMenusList() {
      try {
        const { data } = await getMenusList()
        // console.log(data)
        this.newMenuslist = data
        const str = JSON.stringify(data)
        // console.log(str)
        const newStr = str.replace(/points/g, 'childs')
        this.menuslist = JSON.parse(newStr)

        setTimeout(() => {
          const expand = document.querySelectorAll('.el-table__expand-icon--expanded')
          for (let i = 0; i < expand.length; i++) {
            expand[i].classList.add('active')
          }
        }, 0)
      } catch (error) {
        this.$message('获取菜单列表失败')
      }
    },

    // 添加权限点，选中二级
    async onAddPoints() {
      try {
        const { data } = await currentAdd({
          is_point: true,
          pid: this.cateId,
          code: this.addMenus.code,
          title: this.addMenus.title
        })
        // console.log(data)
        this.loadMenusList()
        this.$message.success('添加成功')
        this.addDialogVisible = false
      } catch (error) {}
    },

    // 添加菜单事件，可以选中一级，也可以选中二级
    addMenusEvent() {
      this.$refs.addFormRef.validate(async valid => {
        // 选中一级触发，添加菜单
        if (this.selectKeys.length === 1) {
          try {
            const { data } = await currentAdd({
              is_point: false,
              pid: this.cateId,
              code: this.addMenus.code,
              title: this.addMenus.title
            })
            // console.log(data)
            this.loadMenusList()
            this.$message.success('添加成功')
            this.addDialogVisible = false
          } catch (error) {}
        } else {
          // 选中二级触发，添加权限点
          this.onAddPoints()
        }
      })
    },

    // 增加表单、权限点状态
    onAddMenus() {
      if (this.type === 'menus') {
        this.addMenusEvent()
      } else {
        this.onAddPoints()
      }
    },

    // 重置表单
    addDialogVisibleClosed() {
      this.$refs.addFormRef.resetFields()
      this.selectKeys = []
    },

    // 监听编辑事件，为表单赋值
    async onEditMenus(role) {
      // 设定表单与权限点，为其单选框赋值
      this.type = role.is_point ? 'points' : 'menus'
      // 为其级联选择器赋值
      this.selectKeys.push(role.id)
      try {
        const { data } = await getDetail({
          id: role.id
        })
        this.editMenus = data
        this.editDialogVisible = true
      } catch (error) {}
    },

    // 重置表单
    editDialogVisibleClosed() {
      this.$refs.editFormRef.resetFields()
      this.selectKeys = []
    },

    // 修改表单
    async sureEditMents() {
      try {
        const { data } = await updateMenus(this.editMenus)
        // console.log(data)
        this.loadMenusList()
        this.editDialogVisible = false
        this.$message.success('修改成功')
      } catch (error) {}
    },

    // 删除菜单
    async deleteMenus(role) {
      try {
        const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (confirmResult !== 'confirm') return this.$message('已取消操作')
        const { data } = await removeMenus({ id: role.id })
        this.$message.success('删除成功')
        this.loadMenusList()
      } catch (error) {
        this.$message('删除失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  .addBtn {
    float: right;
    margin-bottom: 20px;
  }
  ::v-deep.el-table__expand-icon--expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  ::v-deep.btn {
    text-align: center;
  }
  ::v-deep.active {
    display: none;
  }
  .el-form {
    width: 400px;
    margin-left: 150px;
    .el-input {
      width: 280px;
    }
  }
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }
  .menus-icon {
    margin-right: 5px;
    font-size: 16px;
  }
  .el-icon-view {
    margin-left: 20px;
  }
  .fa-file-o {
    margin-left: 10px;
  }
  ::v-deep.el-table__placeholder {
    width: 0;
  }
}
</style>